var app = angular.module('zhijiaoAdminApp.directives');

app.directive('uploadOss' , ['layerService', 'toastPCService',function(layer , toast){
    return {
        restrict : 'A',
        scope : {
            ngModel : '=',
            uploadIng : '=',
        },
        //attr需要id
        link : function(scope , element , attr){

            var accept = attr.accept;
            now = timestamp = Date.parse(new Date()) / 1000;



            function set_upload_param(up, filename, ret){
                up.setOption({
                    'url': '/common/upload/uploadFile'
                });
                up.start();
            }

            var fileType = { //只允许上传图片和zip文件
                image : { title : "Image files", extensions : "jpg,gif,png,bmp,jpeg" },
                docx : { title : "Doc files", extensions : "doc,docx" },
                xlsx : { title : "Doc files", extensions : "xlx,xlsx" },
                video : { title : 'VIdeo files' , extensions : "mp4,avi,m4v"},
                mp3 : { title : 'VIdeo files' , extensions : "mp3"},
                // tif : { title : 'tif files' , extensions : "tiff"},
            };

            var types = [];
            accept.split('|').forEach(item => {
                types.push(fileType[item]);
            })

            var uploader = new plupload.Uploader({
                runtimes : 'html5,flash,silverlight,html4',
                browse_button : attr.id,
                //multi_selection: false,
                // container: document.getElementById('container'),
                flash_swf_url : window._host+'/static/public/js/plupload-2.1.2/js/Moxie.swf',
                silverlight_xap_url : window._host+'/static/public/js/plupload-2.1.2/js/Moxie.xap',
                filters: {

                    mime_types : types,
                    max_file_size : '100mb', //最大只能上传10mb的文件
                    prevent_duplicates : true //不允许选取重复文件
                },
                resize:{
                    crop: true,
                    quality: 80,
                    preserve_headers: false
                },
                init: {
                    PostInit: function() {
                        console.log('init')
                    },

                    FilesAdded: function(up, files) {
                        plupload.each(files, function(file) {
                            var innerHTML = '<div class="progress_box" id="' + file.id + '"><b></b>'
                                +'<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>'
                                +'</div>';
                            element.find('.progress_box').remove();
                            element.parents('.row_progress_box').after(innerHTML)
                            set_upload_param(uploader, files['0'].name, false);
                        });
                    },

                    BeforeUpload: function(up, file) {
                        // console.log(file)
                        //set_upload_param(up, file.name, true);
                    },

                    //实时显示上传进度
                    UploadProgress: function(up, file) {
                        scope.$apply(function(){
                            scope.uploadIng = 1;
                        })
                        var d = document.getElementById(file.id);
                        d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
                        var prog = d.getElementsByTagName('div')[0];
                        var progBar = prog.getElementsByTagName('div')[0]
                        progBar.style.width= 2*file.percent+'px';
                        progBar.setAttribute('aria-valuenow', file.percent);
                    },

                    FileUploaded: function(up, file, info) {
                        if (info.status == 200){
                            var d = document.getElementById(file.id);
                            var prog = d.getElementsByTagName('div')[0];
                            var progBar = prog.getElementsByTagName('div')[0]
                            progBar.style.width= 100+'%';
                            d.remove()
                            toast.show('上传成功');
                            var resp =  JSON.parse(info.response)
                            scope.$apply(function(){
                                scope.uploadIng = 0;
                                scope.ngModel = resp.data.url;
                                // scope.ngModel = host+'/'+g_object_name;
                            })
                        }
                        else{
                            toast.show(2 , '文件上传失败');
                        }
                    },

                    Error: function(up, err) {
                        if (err.code == -600) {
                            toast.show(2 , '选择的文件不得超过'+scope.maxFileSize+'MB');
                        }
                        else if (err.code == -601) {
                            toast.show(2 , '选择的文件后缀不对');
                        }
                        else if (err.code == -602) {
                            toast.show(2 , '这个文件已经上传过一遍了');
                        }
                        else{
                            toast.show(2 , err.response);
                        }
                    }
                }
            });
            uploader.init();

        }
    }
}])